/*
Copyright © 2025 NAME HERE <EMAIL ADDRESS>
*/
package global

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"strings"

	"github.com/spf13/cobra"
	"nodemessage.com/ruov-cli/consts"
	"nodemessage.com/ruov-cli/rlog"
)

// UninstallCmd represents the uninstall command
var UninstallCmd = &cobra.Command{
	Use:   "uninstall",
	Short: "卸载环境变量设置",
	Long:  `移除已安装的环境变量设置，取消全局可用性`,
	Run: func(cmd *cobra.Command, args []string) {
		uninstallGlobal()
	},
}

// uninstallGlobal 将程序从系统环境变量路径移除
func uninstallGlobal() {
	// 根据操作系统类型执行不同的操作
	if runtime.GOOS == "windows" {
		uninstallWindows()
	} else {
		uninstallUnix()
	}
}

// uninstallWindows 在Windows系统中移除PATH环境变量中的设置
func uninstallWindows() {
	binDir := filepath.Join(consts.RootPath, "bin")

	// 清理目录中的文件
	if _, err := os.Stat(binDir); err == nil {
		files, err := os.ReadDir(binDir)
		if err == nil {
			for _, file := range files {
				filePath := filepath.Join(binDir, file.Name())
				os.Remove(filePath)
				rlog.Logger.Warn("已移除文件: %s", filePath)
			}
		}

		// 尝试删除bin目录
		err = os.Remove(binDir)
		if err == nil {
			rlog.Logger.Info("已移除目录: %s", binDir)
		}
	}

	// 从PATH环境变量中移除RUOV_HOME\bin
	pathCmd := fmt.Sprintf(`
$path = [Environment]::GetEnvironmentVariable('Path', 'User')
$ruovPath = '%%RUOV_HOME%%\bin'
if ($path -like "*$ruovPath*") {
    $newPath = ($path -split ';' | Where-Object { $_ -ne $ruovPath }) -join ';'
    [Environment]::SetEnvironmentVariable('Path', $newPath, 'User')
    Write-Output "已从PATH移除"
}`)
	cmd := exec.Command("powershell", "-Command", pathCmd)
	cmd.Run()

	// 移除RUOV_HOME环境变量
	homeCmd := "[Environment]::SetEnvironmentVariable('RUOV_HOME', $null, 'User')"
	cmd = exec.Command("powershell", "-Command", homeCmd)
	cmd.Run()

	rlog.Logger.Info("已成功移除环境变量设置")
	rlog.Logger.Warn("需要重新启动命令提示符或PowerShell才能使环境变量更改生效")
}

// uninstallUnix 在Unix/Linux系统中移除PATH环境变量设置
func uninstallUnix() {
	binDir := filepath.Join(consts.RootPath, "bin")

	// 清理目录中的文件
	if _, err := os.Stat(binDir); err == nil {
		files, err := os.ReadDir(binDir)
		if err == nil {
			for _, file := range files {
				filePath := filepath.Join(binDir, file.Name())
				os.Remove(filePath)
				rlog.Logger.Warn("已移除文件: %s", filePath)
			}
		}

		// 尝试删除bin目录
		err = os.Remove(binDir)
		if err == nil {
			rlog.Logger.Info("已移除目录: %s", binDir)
		}
	}

	// 尝试从shell配置文件中移除环境变量设置
	homeDir, err := os.UserHomeDir()
	if err != nil {
		rlog.Logger.Warn("无法获取用户主目录，请手动从shell配置文件中移除RUOV_HOME和PATH设置")
		return
	}

	// 检查常见的shell配置文件
	shellFiles := []string{".bashrc", ".zshrc", ".profile"}
	for _, file := range shellFiles {
		shellFilePath := filepath.Join(homeDir, file)
		if _, err := os.Stat(shellFilePath); err == nil {
			// 读取文件内容
			content, err := os.ReadFile(shellFilePath)
			if err != nil {
				continue
			}

			// 移除RUOV_HOME和PATH设置
			lines := strings.Split(string(content), "\n")
			newLines := make([]string, 0, len(lines))
			skip := false

			for _, line := range lines {
				if strings.Contains(line, "ruov-cli 环境变量") {
					skip = true
					continue
				}

				if skip && (strings.Contains(line, "RUOV_HOME") || strings.Contains(line, "PATH") && strings.Contains(line, "RUOV_HOME")) {
					continue
				}

				if skip && line == "" {
					skip = false
					continue
				}

				newLines = append(newLines, line)
			}

			// 写回文件
			newContent := strings.Join(newLines, "\n")
			err = os.WriteFile(shellFilePath, []byte(newContent), 0644)
			if err == nil {
				rlog.Logger.Info("已从 %s 移除环境变量设置", shellFilePath)
			}
		}
	}

	rlog.Logger.Info("已成功移除环境变量设置")
	rlog.Logger.Warn("请执行 'source ~/.bashrc' (或其他shell配置文件) 或重新打开终端以使环境变量更改生效")
}
